;;; cstol.el --- Cstol code editing commands for Emacs

;; Author: Brian Overstreet

;; Keywords: languages cstol modes

;; Usage: add the following to the .emacs file:
;; ;; CSTOL-mode
;; (require 'cstol-mode)

;;; Code:

;;
;; User variables.
;;

(defgroup cstol nil
  "Major mode for editing Cstol source in Emacs."
  :link '(custom-group-link :tag "Font Lock Faces group" font-lock-faces)
  :group 'languages)

(defcustom cstol-indent-level 4
  "*Indentation of Cstol statements with respect to containing block."
  :type 'integer
  :group 'cstol)
(put 'cstol-indent-level 'safe-local-variable 'integerp)

(defcustom cstol-continued-indent-level 4
  "*Indentation of continuation line relative to first line of command."
  :type 'integer
  :group 'cstol)
(put 'cstol-continued-indent-level 'safe-local-variable 'integerp)

(defcustom cstol-auto-newline nil
  "*Non-nil means automatically newline before and after braces you insert."
  :type 'boolean
  :group 'cstol)

(defcustom cstol-tab-always-indent tab-always-indent
  "*Control effect of TAB key.
If t (the default), always indent current line.
If nil and point is not in the indentation area at the beginning of
the line, a TAB is inserted.
Other values cause the first possible action from the following list
to take place:

  1. Move from beginning of line to correct indentation.
  2. Delete an empty comment.
  3. Move forward to start of comment, indenting if necessary.
  4. Move forward to end of line, indenting if necessary.
  5. Create an empty comment.
  6. Move backward to start of comment, indenting if necessary."
  :type '(choice (const :tag "Always" t)
		 (const :tag "Beginning only" nil)
		 (const :tag "Maybe move or make or delete comment" 'cstol))
  :group 'cstol)


(defcustom cstol-electric-hash-style nil ;; 'smart
  "*Style of electric hash insertion to use.
Possible values are `backslash', meaning that `\\' quoting should be
done; `quote', meaning that `\"' quoting should be done; `smart',
meaning that the choice between `backslash' and `quote' should be
made depending on the number of hashes inserted; or nil, meaning that
no quoting should be done.  Any other value for this variable is
taken to mean `smart'.  The default is nil."
  :type '(choice (const backslash) (const quote) (const smart) (const nil))
  :group 'cstol)

(defcustom cstol-use-smart-word-finder t
  "*If not nil, use smart way to find current word, for Cstol help feature."
  :type 'boolean
  :group 'cstol)

(defcustom cstol-application "oasis"
  "*Name of Cstol program to run in inferior Cstol mode."
  :type 'string
  :group 'cstol)

(defcustom cstol-command-switches nil
  "*List of switches to supply to the `cstol-application' program."
  :type '(repeat string)
  :group 'cstol)

(defcustom cstol-prompt-regexp "^\\(% \\|\\)"
  "*If not nil, a regexp that will match the prompt in the inferior process.
If nil, the prompt is the name of the application with \">\" appended.

The default is \"^\\(% \\|\\)\", which will match the default primary
and secondary prompts for cstolsh and wish."
  :type 'regexp
  :group 'cstol)

(defcustom inferior-cstol-source-command "source %s\n"
  "*Format-string for building a Cstol command to load a file.
This format string should use `%s' to substitute a file name
and should result in a Cstol expression that will command the
inferior Cstol to load that file.  The filename will be appropriately
quoted for Cstol."
  :type 'string
  :group 'cstol)

(defface cstol-escaped-newline '((t :inherit font-lock-string-face))
  "Face used for (non-escaped) backslash at end of a line in Cstol mode."
  :group 'cstol
  :version "22.1")

;;
;; Keymaps, abbrevs, syntax tables.
;;

(defvar cstol-mode-map
  (let ((map (make-sparse-keymap)))
    (define-key map "{" 'cstol-electric-char)
    (define-key map "}" 'cstol-electric-brace)
    (define-key map "[" 'cstol-electric-char)
    (define-key map "]" 'cstol-electric-char)
    (define-key map "\e\C-q" 'cstol-indent-exp)
    (define-key map "\177" 'backward-delete-char-untabify)
    (define-key map "\t" 'cstol-indent-command)
    (define-key map "\M-\C-x" 'cstol-eval-defun)
    (define-key map "\C-c\C-i" 'cstol-help-on-word)
    (define-key map "\C-c\C-v" 'cstol-eval-defun)
    (define-key map "\C-c\C-f" 'cstol-load-file)
    (define-key map "\C-c\C-t" 'inferior-cstol)
    (define-key map "\C-c\C-x" 'cstol-eval-region)
    (define-key map "\C-c\C-s" 'switch-to-cstol)
    (define-key map "\C-c\C-c" 'comment-region)
    map)
  "Keymap used in `cstol-mode'.")

(defvar cstol-mode-syntax-table
  (let ((st (make-syntax-table)))
    (modify-syntax-entry ?%  "_"  st)
    (modify-syntax-entry ?@  "_"  st)
    (modify-syntax-entry ?&  "_"  st)
    (modify-syntax-entry ?*  "_"  st)
    (modify-syntax-entry ?+  "_"  st)
    (modify-syntax-entry ?-  "_"  st)
    (modify-syntax-entry ?.  "_"  st)
    (modify-syntax-entry ?:  "_"  st)
    (modify-syntax-entry ?!  "_"  st)
    (modify-syntax-entry ?$  "_"  st)	; FIXME use "'"?
    (modify-syntax-entry ?/  "_"  st)
    (modify-syntax-entry ?~  "_"  st)
    (modify-syntax-entry ?<  "_"  st)
    (modify-syntax-entry ?=  "_"  st)
    (modify-syntax-entry ?>  "_"  st)
    (modify-syntax-entry ?|  "_"  st)
    (modify-syntax-entry ?\( "()" st)
    (modify-syntax-entry ?\) ")(" st)
    (modify-syntax-entry ?# "."  st)
    (modify-syntax-entry ?\n ">"  st)
    ;; (modify-syntax-entry ?\f ">"  st)
    (modify-syntax-entry ?\;  "<"  st)
    st)
  "Syntax table in use in `cstol-mode' buffers.")

(defvar inferior-cstol-mode-map
  ;; FIXME we override comint keybindings here.
  ;; Maybe someone has a better set?
  (let ((map (make-sparse-keymap)))
    ;; Will inherit from `comint-mode-map' thanks to define-derived-mode.
    (define-key map "\t" 'comint-dynamic-complete)
    (define-key map "\M-?" 'comint-dynamic-list-filename-completions)
    (define-key map "\177" 'backward-delete-char-untabify)
    (define-key map "\M-\C-x" 'cstol-eval-defun)
    (define-key map "\C-c\C-i" 'cstol-help-on-word)
    (define-key map "\C-c\C-v" 'cstol-eval-defun)
    (define-key map "\C-c\C-f" 'cstol-load-file)
    (define-key map "\C-c\C-t" 'inferior-cstol)
    (define-key map "\C-c\C-x" 'cstol-eval-region)
    (define-key map "\C-c\C-s" 'switch-to-cstol)
    map)
  "Keymap used in `inferior-cstol-mode'.")

(easy-menu-define cstol-mode-menu cstol-mode-map "Menu used in `cstol-mode'."
  '("CSTOL"
    ["Beginning of function" beginning-of-defun t]
    ["End of function" end-of-defun t]
    ["Mark function" mark-defun t]
    ["Indent region" indent-region (mark t)]
    ["Comment region" comment-region (mark t)]
    ["Uncomment region" uncomment-region (mark t)]
    "----"
    ["Show Cstol process buffer" inferior-cstol t]
    ["Send function to Cstol process" cstol-eval-defun
     (and inferior-cstol-buffer (get-buffer inferior-cstol-buffer))]
    ["Send region to Cstol process" cstol-eval-region
     (and inferior-cstol-buffer (get-buffer inferior-cstol-buffer))]
    ["Send file to Cstol process" cstol-load-file
     (and inferior-cstol-buffer (get-buffer inferior-cstol-buffer))]
    ["Restart Cstol process with file" cstol-restart-with-file t]
    "----"
    ["Cstol help" cstol-help-on-word cstol-help-directory-list]))

(defvar inferior-cstol-buffer nil
  "*The current inferior-cstol process buffer.

MULTIPLE PROCESS SUPPORT
===========================================================================
To run multiple Cstol processes, you start the first up with
\\[inferior-cstol].  It will be in a buffer named `*inferior-cstol*'.
Rename this buffer with \\[rename-buffer].  You may now start up a new
process with another \\[inferior-cstol].  It will be in a new buffer,
named `*inferior-cstol*'.  You can switch between the different process
buffers with \\[switch-to-buffer].

Commands that send text from source buffers to Cstol processes -- like
`cstol-eval-defun' or `cstol-load-file' -- have to choose a process to
send to, when you have more than one Cstol process around.  This is
determined by the global variable `inferior-cstol-buffer'.  Suppose you
have three inferior Lisps running:
    Buffer              Process
    foo                 inferior-cstol
    bar                 inferior-cstol<2>
    *inferior-cstol*      inferior-cstol<3>
If you do a \\[cstol-eval-defun] command on some Lisp source code, what
process do you send it to?

- If you're in a process buffer (foo, bar, or *inferior-cstol*),
  you send it to that process.
- If you're in some other buffer (e.g., a source file), you
  send it to the process attached to buffer `inferior-cstol-buffer'.
This process selection is performed by function `inferior-cstol-proc'.

Whenever \\[inferior-cstol] fires up a new process, it resets
`inferior-cstol-buffer' to be the new process's buffer.  If you only run
one process, this does the right thing.  If you run multiple
processes, you can change `inferior-cstol-buffer' to another process
buffer with \\[set-variable].")

;;
;; Hooks and other customization.
;;

(defvar cstol-mode-hook nil
  "Hook run on entry to Cstol mode.

Several functions exist which are useful to run from your
`cstol-mode-hook' (see each function's documentation for more
information):

  `cstol-guess-application'
    Guesses a default setting for `cstol-application' based on any
    \"#!\" line at the top of the file.
  `cstol-hashify-buffer'
    Quotes all \"#\" characters that don't correspond to actual
    Cstol comments.  (Useful when editing code not originally created
    with this mode).
  `cstol-auto-fill-mode'
    Auto-filling of Cstol comments.

Add functions to the hook with `add-hook':

   (add-hook 'cstol-mode-hook 'cstol-guess-application)")


(defvar cstol-proc-list
  '("proc" "declare variable")
  "List of commands whose first argument defines something.
This exists because some people (eg, me) use `defvar' et al.
Call `cstol-set-proc-regexp' and `cstol-set-font-lock-keywords'
after changing this list.")

(defvar cstol-proc-regexp nil
  "Regexp to use when matching proc headers.")

(defvar cstol-typeword-list
  '("global" "upvar" "inherit" "public" "protected" "private"
    "common" "itk_option" "variable")
  "List of Cstol keywords denoting \"type\".  Used only for highlighting.
Call `cstol-set-font-lock-keywords' after changing this list.")

;; Generally I've picked control operators to be keywords.
(defvar cstol-keyword-list
  '("if" "then" "else" "elseif" "endif" "endproc" "for" "foreach" "break" 
    "continue" "while" "begin"
    "eval" "case" "in" "switch" "default" "exit" "error" "proc" "return"
    "uplevel" "constructor" "destructor" "icstol_class" "loop" "for_array_keys"
    "for_recursive_glob" "for_file" "method" "body" "configbody" "class"
    "chain")
  "List of Cstol keywords.  Used only for highlighting.
Call `cstol-set-font-lock-keywords' after changing this list.")

(defvar cstol-builtin-list
  '("let" "declare" "write" "end" "&" "variable" "lock"
  "restore" "delete" "commit" "unlock" "update" "show" "to" "with"
  "by" "from" "and" "send" "move" "now" "clear" "load" "ask" "wait"
  "cancel" "checkpoint" "clear" "check" "hold" "compile" "cstol"
  "decompile" "define" "display" "loop" "escape" "flush" "go"
  "initialize" "load" "lock" "unlock" "macro" "make" "message" "send"
  "poll" "record" "report" "restore" "retrieve" "retry" "return"
  "route" "run" "sample" "show" "snap" "start" "stop" "switch"
  "undefine" "update" "new_proc" "insert")
  "List of Cstol commands.  Used only for highlighting.
Call `cstol-set-font-lock-keywords' after changing this list.
This list excludes those commands already found in `cstol-proc-list' and
`cstol-keyword-list'.")

(defvar cstol-constant-list
  '("activate" "arm" "boot" "change" "close" "disable" "disarm" "drive" "dump" "enable" "fire" "flyback" "force" "off" "force" "on" "get" "halt" "ignore" "initiate" "move" "open" "pass" "perform" "reset" "select" "set" "slew" "step" "test" "toggle" "turn" "use" "fast" "medium" "slow" "backward" "forward" "up" "down" "left" "where" "right" "in" "out" "cw" "ccw" "all" "procedures" "at" "always" "last")
  "List of Cstol constants.  Used only for highlighting.
Call `cstol-set-font-lock-keywords' after changing this list.
This list excludes those commands already found in `cstol-proc-list' and
`cstol-keyword-list'.")

(defvar cstol-font-lock-keywords nil
  "Keywords to highlight for Cstol.  See variable `font-lock-keywords'.
This variable is generally set from `cstol-proc-regexp',
`cstol-typeword-list', and `cstol-keyword-list' by the function
`cstol-set-font-lock-keywords'.")

(defvar cstol-font-lock-syntactic-keywords
  ;; Mark the few `#' that are not comment-markers.
  '(("[{ \t\n][ \t]*\\(#\\)" (1 ".")))
  "Syntactic keywords for `cstol-mode'.")

;; FIXME need some way to recognize variables because array refs look
;; like 2 sexps.
(defvar cstol-type-alist
  '(("proc" nil cstol-expr cstol-commands)
    ("method" nil cstol-expr cstol-commands)
    ("destructor" cstol-commands)
    ("constructor" cstol-commands)
    ("expr" cstol-expr)
    ("catch" cstol-commands)
    ("if" cstol-expr "then" cstol-commands)
    ("elseif" cstol-expr "then" cstol-commands)
    ("elseif" cstol-expr cstol-commands)
    ("if" cstol-expr cstol-commands)
    ("while" cstol-expr cstol-commands)
    ("for" cstol-commands cstol-expr cstol-commands cstol-commands)
    ("foreach" nil nil cstol-commands)
    ("for_file" nil nil cstol-commands)
    ("for_array_keys" nil nil cstol-commands)
    ("for_recursive_glob" nil nil nil cstol-commands)
    ;; Loop handling is not perfect, because the third argument can be
    ;; either a command or an expr, and there is no real way to look
    ;; forward.
    ("loop" nil cstol-expr cstol-expr cstol-commands)
    ("loop" nil cstol-expr cstol-commands))
  "Alist that controls indentation.
\(Actually, this really only controls what happens on continuation lines).
Each entry looks like `(KEYWORD TYPE ...)'.
Each type entry describes a sexp after the keyword, and can be one of:
* nil, meaning that this sexp has no particular type.
* cstol-expr, meaning that this sexp is an arithmetic expression.
* cstol-commands, meaning that this sexp holds Cstol commands.
* a string, which must exactly match the string at the corresponding
  position for a match to be made.

For example, the entry for the \"loop\" command is:

   (\"loop\" nil cstol-expr cstol-commands)

This means that the \"loop\" command has three arguments.  The first
argument is ignored (for indentation purposes).  The second argument
is a Cstol expression, and the last argument is Cstol commands.")

(defvar cstol-explain-indentation nil
  "If non-nil, debugging message will be printed during indentation.")



;; Here's another stab.  I think this one actually works.
;; We have to be careful that the open-brace following this regexp
;; is indeed the one corresponding to the function's body so
;; that end-of-defun works correctly.  Tricky cases are:
;;    proc foo { {arg1 def} arg2 } {
;; as well as
;;    proc foo { \n {arg1 def} \n arg2 } {
;; The current setting handles the first case properly but not the second.
;; It also fails if `proc' is not in column-0 (e.g. it's in a namespace).
(defconst cstol-omit-ws-regexp "^[^]\" \t\n#}][^\n\"#]+[ \t]+")



;;
;; Some helper functions.
;;
(defface cstol-strong-face '((t (:inherit bold)))
  "`cstol-mode' face used to highlight keywords")
(defvar cstol-strong-face 'cstol-strong-face)


(defun cstol-set-proc-regexp ()
  "Set `cstol-proc-regexp' from variable `cstol-proc-list'."
  (setq cstol-proc-regexp
	(concat "^\\s-*" (regexp-opt cstol-proc-list t) "[ \t]+")))

(defun cstol-set-font-lock-keywords ()
  "Set `cstol-font-lock-keywords'.
Uses variables `cstol-proc-regexp' and `cstol-keyword-list'."
  (setq cstol-font-lock-keywords
	(list
	 ;; Names of functions (and other "defining things").
	 (list (concat cstol-proc-regexp "\\([^ \t\n]+\\)")
	       2 'font-lock-function-name-face)

	 ;; Names of type-defining things.
	 (list (concat "\\(\\s-\\|^\\)"
		       (regexp-opt cstol-typeword-list t)
		       "\\(\\s-\\|$\\)")
	       2 'font-lock-type-face)

         (list (concat "\\_<" (regexp-opt cstol-builtin-list t) "\\_>")
	       1 'font-lock-builtin-face)

         (list (concat "\\_<" (regexp-opt cstol-constant-list t) "\\_>")
	       0 'cstol-strong-face)

         ;; When variable names are enclosed in {} braces, any
         ;; character can be used. Otherwise just letters, digits,
         ;; underscores.  Variable names can be prefixed with any
         ;; number of "namespace::" qualifiers.  A leading "::" refers
         ;; to the global namespace.
         '("\\${\\([^}]+\\)}" 1 font-lock-variable-name-face)
         '("\\$\\(\\(?:::\\)?\\(?:[[:alnum:]_]+::\\)*[[:alnum:]_]+\\)"
           1 font-lock-variable-name-face)
         '("\\(?:\\s-\\|^\\|\\[\\)set\\s-+{\\([^}]+\\)}"
           1 font-lock-variable-name-face keep)
         '("\\(?:\\s-\\|^\\|\\[\\)set\\s-+\\(\\(?:::\\)?\
\\(?:[[:alnum:]_]+::\\)*[[:alnum:]_]+\\)"
           1 font-lock-variable-name-face keep)

         '("\\(^\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\)$" 3 'cstol-escaped-newline)

	 ;; Keywords.  Only recognized if surrounded by whitespace.
	 ;; FIXME consider using "not word or symbol", not
	 ;; "whitespace".
	 (cons (concat "\\_<" (regexp-opt cstol-keyword-list t) "\\_>")
	       1))))

(if cstol-proc-regexp
    ()
  (cstol-set-proc-regexp))

(if cstol-font-lock-keywords
    ()
  (cstol-set-font-lock-keywords))


(defvar cstol-imenu-generic-expression
  `((nil ,(concat cstol-proc-regexp "\\([-A-Za-z0-9_:+*]+\\)") 2))
  "Imenu generic expression for `cstol-mode'.  See `imenu-generic-expression'.")



;;
;; The mode itself.
;;

;;;###autoload
(define-derived-mode cstol-mode nil "CSTOL"
  "Major mode for editing Cstol code.
Expression and list commands understand all Cstol brackets.
Tab indents for Cstol code.
Paragraphs are separated by blank lines only.
Delete converts tabs to spaces as it moves back.

Variables controlling indentation style:
  `cstol-indent-level'
    Indentation of Cstol statements within surrounding block.
  `cstol-continued-indent-level'
    Indentation of continuation line relative to first line of command.

Variables controlling user interaction with mode (see variable
documentation for details):
  `cstol-tab-always-indent'
    Controls action of TAB key.
  `cstol-auto-newline'
    Non-nil means automatically newline before and after braces, brackets,
    and semicolons inserted in Cstol code.
  `cstol-use-smart-word-finder'
    If not nil, use a smarter, Cstol-specific way to find the current
    word when looking up help on a Cstol command.

Turning on Cstol mode runs `cstol-mode-hook'.  Read the documentation for
`cstol-mode-hook' to see what kinds of interesting hook functions
already exist.

Commands:
\\{cstol-mode-map}"
  (unless (and (boundp 'filladapt-mode) filladapt-mode)
    (set (make-local-variable 'paragraph-ignore-fill-prefix) t))

  (set (make-local-variable 'indent-line-function) 'cstol-indent-line)
  (set (make-local-variable 'comment-indent-function) 'cstol-comment-indent)
  ;; Cstol doesn't require a final newline.
  ;; (make-local-variable 'require-final-newline)
  ;; (setq require-final-newline t)

  (set (make-local-variable 'comment-start) ";")
;  (set (make-local-variable 'comment-start-skip)
;       "\\(\\(^\\|[;{[]\\)\\s-*\\)#+ *")
  (set (make-local-variable 'comment-end) "")

  (set (make-local-variable 'outline-regexp) ".")
  (set (make-local-variable 'outline-level) 'cstol-outline-level)

  (set (make-local-variable 'font-lock-defaults)
       '(cstol-font-lock-keywords nil nil nil beginning-of-defun
 	 (font-lock-syntactic-keywords . cstol-font-lock-syntactic-keywords)
 	 (parse-sexp-lookup-properties . t)))

  (set (make-local-variable 'imenu-generic-expression)
       cstol-imenu-generic-expression)

  ;; Settings for new dabbrev code.
  (set (make-local-variable 'dabbrev-case-fold-search) nil)
  (set (make-local-variable 'dabbrev-case-replace) nil)
  (set (make-local-variable 'dabbrev-abbrev-skip-leading-regexp) "[$!]")
  (set (make-local-variable 'dabbrev-abbrev-char-regexp) "\\sw\\|\\s_")

  ;; This can only be set to t in Emacs 19 and XEmacs.
  ;; Emacs 18 and Epoch lose.
  (set (make-local-variable 'parse-sexp-ignore-comments) t)
  ;; XEmacs has defun-prompt-regexp, but I don't believe
  ;; that it works for end-of-defun -- only for
  ;; beginning-of-defun.
  (set (make-local-variable 'defun-prompt-regexp) cstol-omit-ws-regexp)
  ;; The following doesn't work in Lucid Emacs 19.6, but maybe
  ;; it will appear in later versions.
  (set (make-local-variable 'add-log-current-defun-function)
       'cstol-add-log-defun)

  (easy-menu-add cstol-mode-menu)
  ;; Append Cstol menu to popup menu for XEmacs.
  (if (boundp 'mode-popup-menu)
      (setq mode-popup-menu
	    (cons (concat mode-name " Mode Commands") cstol-mode-menu))))



;; This is used for braces, brackets, and semi (except for closing
;; braces, which are handled specially).
(defun cstol-electric-char (arg)
  "Insert character and correct line's indentation."
  (interactive "p")
  ;; Indent line first; this looks better if parens blink.
  (cstol-indent-line)
  (self-insert-command arg)
  (if (and cstol-auto-newline (= last-command-char ?\;))
      (progn
	(newline)
	(cstol-indent-line))))

;; This is used for closing braces.  If cstol-auto-newline is set, can
;; insert a newline both before and after the brace, depending on
;; context.  FIXME should this be configurable?  Does anyone use this?
(defun cstol-electric-brace (arg)
  "Insert character and correct line's indentation."
  (interactive "p")
  ;; If auto-newlining and there is stuff on the same line, insert a
  ;; newline first.
  (if cstol-auto-newline
      (progn
	(if (save-excursion
	      (skip-chars-backward " \t")
	      (bolp))
	    ()
	  (cstol-indent-line)
	  (newline))
	;; In auto-newline case, must insert a newline after each
	;; brace.  So an explicit loop is needed.
	(while (> arg 0)
	  (insert last-command-char)
	  (cstol-indent-line)
	  (newline)
	  (setq arg (1- arg))))
    (self-insert-command arg))
  (cstol-indent-line))



(defun cstol-indent-command (&optional arg)
  "Indent current line as Cstol code, or in some cases insert a tab character.
If `cstol-tab-always-indent' is t (the default), always indent current line.
If `cstol-tab-always-indent' is nil and point is not in the indentation
area at the beginning of the line, a TAB is inserted.
Other values of `cstol-tab-always-indent' cause the first possible action
from the following list to take place:

  1. Move from beginning of line to correct indentation.
  2. Delete an empty comment.
  3. Move forward to start of comment, indenting if necessary.
  4. Move forward to end of line, indenting if necessary.
  5. Create an empty comment.
  6. Move backward to start of comment, indenting if necessary."
  (interactive "p")
  (if (memq cstol-tab-always-indent '(nil t))
      (let ((tab-always-indent cstol-tab-always-indent))
        (call-interactively 'indent-for-tab-command))
    ;; "Perl-mode" style TAB command.
    (let* ((ipoint (point))
	   (eolpoint (progn
		       (end-of-line)
		       (point)))
	   (comment-p (cstol-in-comment)))
      (cond
       ((= ipoint (line-beginning-position))
	(beginning-of-line)
	(cstol-indent-line)
	;; If indenting didn't leave us in column 0, go to the
	;; indentation.  Otherwise leave point at end of line.  This
	;; is a hack.
	(if (= (point) (line-beginning-position))
	    (end-of-line)
	  (back-to-indentation)))
       ((and comment-p (looking-at "[ \t]*$"))
	;; Empty comment, so delete it.  We also delete any ";"
	;; characters at the end of the line.  I think this is
	;; friendlier, but I don't know how other people will feel.
	(backward-char)
	(skip-chars-backward " \t;")
	(delete-region (point) eolpoint))
       ((and comment-p (< ipoint (point)))
	;; Before comment, so skip to it.
	(cstol-indent-line)
	(indent-for-comment))
       ((/= ipoint eolpoint)
	;; Go to end of line (since we're not there yet).
	(goto-char eolpoint)
	(cstol-indent-line))
       ((not comment-p)
	(cstol-indent-line)
	(comment-indent))
       (t
	;; Go to start of comment.  We don't leave point where it is
	;; because we want to skip comment-start-skip.
	(cstol-indent-line)
	(indent-for-comment))))))

(defun cstol-indent-line ()
  "Indent current line as Cstol code.
Return the amount the indentation changed by."
  (let ((indent (cstol-calculate-indent nil))
	beg shift-amt
	(case-fold-search nil)
	(pos (- (point-max) (point))))
    (if (null indent)
        'noindent
      (beginning-of-line)
      (setq beg (point))
      (skip-chars-forward " \t")
      (if (listp indent) (setq indent (car indent)))
      (cond ((= (following-char) ?})
             (setq indent (- indent cstol-indent-level)))
            ((= (following-char) ?\])
             (setq indent (- indent 1))))
      (skip-chars-forward " \t")
      (setq shift-amt (- indent (current-column)))
      (if (zerop shift-amt)
          (if (> (- (point-max) pos) (point))
              (goto-char (- (point-max) pos)))
        (delete-region beg (point))
        (indent-to indent)
        ;; If initial point was within line's indentation,
        ;; position after the indentation.  Else stay at same point in text.
        (if (> (- (point-max) pos) (point))
            (goto-char (- (point-max) pos))))
      shift-amt)))

(defun cstol-figure-type ()
  "Determine type of sexp at point.
This is either `cstol-expr', `cstol-commands', or nil.  Puts point at start
of sexp that indicates types.

See documentation for variable `cstol-type-alist' for more information."
  (let ((count 0)
	result
	word-stack)
    (while (and (< count 5)
		(not result))
      (condition-case nil
	  (progn
	    ;; FIXME should use "cstol-backward-sexp", which would skip
	    ;; over entire variables, etc.
	    (backward-sexp)
	    (if (looking-at "[a-zA-Z_]+")
		(let ((list cstol-type-alist)
		      entry)
		  (setq word-stack (cons (cstol-word-no-props) word-stack))
		  (while (and list (not result))
		    (setq entry (car list))
		    (setq list (cdr list))
		    (let ((index 0))
		      (while (and entry (<= index count))
			;; Abort loop if string does not match word on
			;; stack.
			(and (stringp (car entry))
			     (not (string= (car entry)
					   (nth index word-stack)))
			     (setq entry nil))
			(setq entry (cdr entry))
			(setq index (1+ index)))
		      (and (> index count)
			   (not (stringp (car entry)))
			   (setq result (car entry)))
		      )))
	      (setq word-stack (cons nil word-stack))))
	(error nil))
      (setq count (1+ count)))
    (and cstol-explain-indentation
	 (message "Indentation type %s" result))
    result))

(defun cstol-calculate-indent (&optional parse-start)
  "Return appropriate indentation for current line as Cstol code.
In usual case returns an integer: the column to indent to.
Returns nil if line starts inside a string, t if in a comment."
  (save-excursion
    (beginning-of-line)
    (let* ((indent-point (point))
	   (case-fold-search nil)
	   (continued-line
	    (save-excursion
	      (if (bobp)
		  nil
		(backward-char)
		(= ?\\ (preceding-char)))))
	   (continued-indent-value (if continued-line
				       cstol-continued-indent-level
				     0))
	   state
	   containing-sexp
	   found-next-line)
      (if parse-start
	  (goto-char parse-start)
	(beginning-of-defun))
      (while (< (point) indent-point)
	(setq parse-start (point))
	(setq state (parse-partial-sexp (point) indent-point 0))
	(setq containing-sexp (car (cdr state))))
      (cond ((or (nth 3 state) (nth 4 state))
	     ;; Inside comment or string.  Return nil or t if should
	     ;; not change this line
	     (nth 4 state))
	    ((null containing-sexp)
	     ;; Line is at top level.
	     continued-indent-value)
	    (t
	     ;; Set expr-p if we are looking at the expression part of
	     ;; an "if", "expr", etc statement.  Set commands-p if we
	     ;; are looking at the body part of an if, while, etc
	     ;; statement.  FIXME Should check for "for" loops here.
	     (goto-char containing-sexp)
	     (let* ((sexpr-type (cstol-figure-type))
		    (expr-p (eq sexpr-type 'cstol-expr))
		    (commands-p (eq sexpr-type 'cstol-commands))
		    (expr-start (point)))
	       ;; Find the first statement in the block and indent
	       ;; like it.  The first statement in the block might be
	       ;; on the same line, so what we do is skip all
	       ;; "virtually blank" lines, looking for a non-blank
	       ;; one.  A line is virtually blank if it only contains
	       ;; a comment and whitespace.  FIXME continued comments
	       ;; aren't supported.  They are a wart on Cstol anyway.
	       ;; We do it this funky way because we want to know if
	       ;; we've found a statement on some line _after_ the
	       ;; line holding the sexp opener.
	       (goto-char containing-sexp)
	       (forward-char)
	       (if (and (< (point) indent-point)
			(looking-at "[ \t]*\\(#.*\\)?$"))
		   (progn
		     (forward-line)
		     (while (and (< (point) indent-point)
				 (looking-at "[ \t]*\\(#.*\\)?$"))
		       (setq found-next-line t)
		       (forward-line))))
	       (if (or continued-line
		       (/= (char-after containing-sexp) ?{)
		       expr-p)
		   (progn
		     ;; Line is continuation line, or the sexp opener
		     ;; is not a curly brace, or we are are looking at
		     ;; an `expr' expression (which must be split
		     ;; specially).  So indentation is column of first
		     ;; good spot after sexp opener (with some added
		     ;; in the continued-line case).  If there is no
		     ;; nonempty line before the indentation point, we
		     ;; use the column of the character after the sexp
		     ;; opener.
		     (if (>= (point) indent-point)
			 (progn
			   (goto-char containing-sexp)
			   (forward-char))
		       (skip-chars-forward " \t"))
		     (+ (current-column) continued-indent-value))
		 ;; After a curly brace, and not a continuation line.
		 ;; So take indentation from first good line after
		 ;; start of block, unless that line is on the same
		 ;; line as the opening brace.  In this case use the
		 ;; indentation of the opening brace's line, plus
		 ;; another indent step.  If we are in the body part
		 ;; of an "if" or "while" then the indentation is
		 ;; taken from the line holding the start of the
		 ;; statement.
		 (if (and (< (point) indent-point)
			  found-next-line)
		     (current-indentation)
		   (if commands-p
		       (goto-char expr-start)
		     (goto-char containing-sexp))
		   (+ (current-indentation) cstol-indent-level)))))))))



(defun cstol-indent-exp ()
  "Indent each line of the Cstol grouping following point."
  (interactive)
  (let ((indent-stack (list nil))
	(contain-stack (list (point)))
	(case-fold-search nil)
	outer-loop-done inner-loop-done state ostate
	this-indent continued-line
	(next-depth 0)
	last-depth)
    (save-excursion
      (forward-sexp 1))
    (save-excursion
      (setq outer-loop-done nil)
      (while (and (not (eobp)) (not outer-loop-done))
	(setq last-depth next-depth)
	;; Compute how depth changes over this line
	;; plus enough other lines to get to one that
	;; does not end inside a comment or string.
	;; Meanwhile, do appropriate indentation on comment lines.
	(setq inner-loop-done nil)
	(while (and (not inner-loop-done)
		    (not (and (eobp) (setq outer-loop-done t))))
	  (setq ostate state)
	  (setq state (parse-partial-sexp (point) (progn (end-of-line) (point))
					  nil nil state))
	  (setq next-depth (car state))
	  (if (or (nth 4 ostate))
	      (cstol-indent-line))
	  (if (or (nth 3 state))
	      (forward-line 1)
	    (setq inner-loop-done t)))
	(if (<= next-depth 0)
	    (setq outer-loop-done t))
	(if outer-loop-done
	    nil
	  ;; If this line had ..))) (((.. in it, pop out of the levels
	  ;; that ended anywhere in this line, even if the final depth
	  ;; doesn't indicate that they ended.
	  (while (> last-depth (nth 6 state))
	    (setq indent-stack (cdr indent-stack)
		  contain-stack (cdr contain-stack)
		  last-depth (1- last-depth)))
	  ;; Add levels for any parens that were started in this line.
	  (while (< last-depth next-depth)
	    (setq indent-stack (cons nil indent-stack)
		  contain-stack (cons nil contain-stack)
		  last-depth (1+ last-depth)))
	  (if (null (car contain-stack))
	      (setcar contain-stack
		      (or (car (cdr state))
			  (save-excursion
			    (forward-sexp -1)
			    (point)))))
	  (forward-line 1)
	  (setq continued-line
		(save-excursion
		  (backward-char)
		  (= (preceding-char) ?\\)))
	  (skip-chars-forward " \t")
	  (if (eolp)
	      nil
	    (if (and (car indent-stack)
		     (>= (car indent-stack) 0))
		;; Line is on an existing nesting level.
		(setq this-indent (car indent-stack))
	      ;; Just started a new nesting level.
	      ;; Compute the standard indent for this level.
	      (let ((val (cstol-calculate-indent
			  (if (car indent-stack)
			      (- (car indent-stack))))))
		(setcar indent-stack
			(setq this-indent val))
		(setq continued-line nil)))
	    (cond ((not (numberp this-indent)))
		  ((= (following-char) ?})
		   (setq this-indent (- this-indent cstol-indent-level)))
		  ((= (following-char) ?\])
		   (setq this-indent (- this-indent 1))))
	    ;; Put chosen indentation into effect.
	    (or (null this-indent)
		(= (current-column)
		   (if continued-line
		       (+ this-indent cstol-indent-level)
		     this-indent))
		(progn
		  (delete-region (point) (progn (beginning-of-line) (point)))
		  (indent-to
		   (if continued-line
		       (+ this-indent cstol-indent-level)
		     this-indent)))))))))
  )



;;
;; Interfaces to other packages.
;;

;; FIXME Definition of function is very ad-hoc.  Should use
;; beginning-of-defun.  Also has incestuous knowledge about the
;; format of cstol-proc-regexp.
(defun cstol-add-log-defun ()
  "Return name of Cstol function point is in, or nil."
  (save-excursion
    (end-of-line)
    (if (re-search-backward (concat cstol-proc-regexp "\\([^ \t\n{]+\\)") nil t)
	(match-string 2))))

(defun cstol-outline-level ()
  (save-excursion
    (skip-chars-forward " \t")
    (current-column)))



;;
;; Helper functions for inferior Cstol mode.
;;

;; This exists to let us delete the prompt when commands are sent
;; directly to the inferior Cstol.  See gud.el for an explanation of how
;; it all works (I took it from there).  This stuff doesn't really
;; work as well as I'd like it to.  But I don't believe there is
;; anything useful that can be done.
(defvar inferior-cstol-delete-prompt-marker nil)

(defun cstol-filter (proc string)
  (let ((inhibit-quit t))
    (with-current-buffer (process-buffer proc)
      (goto-char (process-mark proc))
      ;; Delete prompt if requested.
      (if (marker-buffer inferior-cstol-delete-prompt-marker)
	  (progn
	    (delete-region (point) inferior-cstol-delete-prompt-marker)
	    (set-marker inferior-cstol-delete-prompt-marker nil)))))
  (comint-output-filter proc string))

(defun cstol-send-string (proc string)
  (with-current-buffer (process-buffer proc)
    (goto-char (process-mark proc))
    (forward-line 0)             ;Not (beginning-of-line) because of fields.
    (if (looking-at comint-prompt-regexp)
	(set-marker inferior-cstol-delete-prompt-marker (point))))
  (comint-send-string proc string))

(defun cstol-send-region (proc start end)
  (with-current-buffer (process-buffer proc)
    (goto-char (process-mark proc))
    (forward-line 0)             ;Not (beginning-of-line) because of fields.
    (if (looking-at comint-prompt-regexp)
	(set-marker inferior-cstol-delete-prompt-marker (point))))
  (comint-send-region proc start end))

(defun switch-to-cstol (eob-p)
  "Switch to inferior Cstol process buffer.
With argument, positions cursor at end of buffer."
  (interactive "P")
  (if (get-buffer inferior-cstol-buffer)
      (pop-to-buffer inferior-cstol-buffer)
    (error "No current inferior Cstol buffer"))
  (cond (eob-p
	 (push-mark)
	 (goto-char (point-max)))))

(defun inferior-cstol-proc ()
  "Return current inferior Cstol process.
See variable `inferior-cstol-buffer'."
  (let ((proc (get-buffer-process (if (eq major-mode 'inferior-cstol-mode)
				      (current-buffer)
				    inferior-cstol-buffer))))
    (or proc
	(error "No Cstol process; see variable `inferior-cstol-buffer'"))))

(defun cstol-eval-region (start end &optional and-go)
  "Send the current region to the inferior Cstol process.
Prefix argument means switch to the Cstol buffer afterwards."
  (interactive "r\nP")
  (let ((proc (inferior-cstol-proc)))
    (cstol-send-region
     proc
     ;; Strip leading and trailing whitespace.
     (save-excursion (goto-char start) (skip-chars-forward " \t\n") (point))
     (save-excursion (goto-char end) (skip-chars-backward " \t\n") (point)))
    (cstol-send-string proc "\n")
    (if and-go (switch-to-cstol t))))

(defun cstol-eval-defun (&optional and-go)
  "Send the current defun to the inferior Cstol process.
Prefix argument means switch to the Cstol buffer afterwards."
  (interactive "P")
  (save-excursion
    (end-of-defun)
    (let ((end (point)))
      (beginning-of-defun)
      (cstol-eval-region (point) end)))
  (if and-go (switch-to-cstol t)))



;;
;; Inferior Cstol mode itself.
;;

(define-derived-mode inferior-cstol-mode comint-mode "Inferior Cstol"
  "Major mode for interacting with Cstol interpreter.

You can start a Cstol process with \\[inferior-cstol].

Entry to this mode runs the normal hooks `comint-mode-hook' and
`inferior-cstol-mode-hook', in that order.

You can send text to the inferior Cstol process from other buffers
containing Cstol source.

Variables controlling Inferior Cstol mode:
  `cstol-application'
    Name of program to run.
  `cstol-command-switches'
    Command line arguments to `cstol-application'.
  `cstol-prompt-regexp'
    Matches prompt.
  `inferior-cstol-source-command'
    Command to use to read Cstol file in running application.
  `inferior-cstol-buffer'
    The current inferior Cstol process buffer.  See variable
    documentation for details on multiple-process support.

The following commands are available:
\\{inferior-cstol-mode-map}"
  (set (make-local-variable 'comint-prompt-regexp)
       (or cstol-prompt-regexp
	   (concat "^" (regexp-quote cstol-application) ">")))
  (setq mode-line-process '(": %s"))
  (setq local-abbrev-table cstol-mode-abbrev-table)
  (set-syntax-table cstol-mode-syntax-table)
  (set (make-local-variable 'defun-prompt-regexp) cstol-omit-ws-regexp)
  (set (make-local-variable 'inferior-cstol-delete-prompt-marker) (make-marker))
  (set-process-filter (get-buffer-process (current-buffer)) 'cstol-filter))

;;;###autoload
(defun inferior-cstol (cmd)
  "Run inferior Cstol process.
Prefix arg means enter program name interactively.
See documentation for function `inferior-cstol-mode' for more information."
  (interactive
   (list (if current-prefix-arg
	     (read-string "Run Cstol: " cstol-application)
	   cstol-application)))
  (unless (comint-check-proc "*inferior-cstol*")
    (set-buffer (apply (function make-comint) "inferior-cstol" cmd nil
		       cstol-command-switches))
    (inferior-cstol-mode)
    ;; Make cstolsh display a prompt on ms-windows (or under Unix, when a tty
    ;; wasn't used).  Doesn't affect wish, unfortunately.
    (unless (process-tty-name (inferior-cstol-proc))
      (cstol-send-string (inferior-cstol-proc)
                       "set ::cstol_interactive 1; concat\n")))
  (set (make-local-variable 'cstol-application) cmd)
  (setq inferior-cstol-buffer "*inferior-cstol*")
  (pop-to-buffer "*inferior-cstol*"))

(defalias 'run-cstol 'inferior-cstol)



;;
;; Auto-fill support.
;;

(defun cstol-real-command-p ()
  "Return nil if point is not at the beginning of a command.
A command is the first word on an otherwise empty line, or the
first word following a semicolon, opening brace, or opening bracket."
  (save-excursion
    (skip-chars-backward " \t")
    (cond
     ((bobp) t)
     ((bolp)
      (backward-char)
      ;; Note -- continued comments are not supported here.  I
      ;; consider those to be a wart on the language.
      (not (eq ?\\ (preceding-char))))
     (t
      (memq (preceding-char) '(?\; ?{ ?\[))))))

;; FIXME doesn't actually return t.  See last case.
(defun cstol-real-comment-p ()
  "Return t if point is just after the `#' beginning a real comment.
Does not check to see if previous char is actually `#'.
A real comment is either at the beginning of the buffer,
preceded only by whitespace on the line, or has a preceding
semicolon, opening brace, or opening bracket on the same line."
  (save-excursion
    (backward-char)
    (cstol-real-command-p)))

(defun cstol-hairy-scan-for-comment (state end always-stop)
  "Determine if point is in a comment.
Returns a list of the form `(FLAG . STATE)'.  STATE can be used
as input to future invocations.  FLAG is nil if not in comment,
t otherwise.  If in comment, leaves point at beginning of comment.

This function does not work in Emacs 18.
See also `cstol-simple-scan-for-comment', a
simpler version that is often right, and works in Emacs 18."
  (let ((bol (save-excursion
	       (goto-char end)
	       (beginning-of-line)
	       (point)))
	real-comment
	last-cstart)
    (while (and (not last-cstart) (< (point) end))
      (setq real-comment nil)	 ;In case we've looped around and it is set.
      (setq state (parse-partial-sexp (point) end nil nil state t))
      (if (nth 4 state)
	  (progn
	    ;; If ALWAYS-STOP is set, stop even if we don't have a
	    ;; real comment, or if the comment isn't on the same line
	    ;; as the end.
	    (if always-stop (setq last-cstart (point)))
	    ;; If we have a real comment, then set the comment
	    ;; starting point if we are on the same line as the ending
	    ;; location.
	    (setq real-comment (cstol-real-comment-p))
	    (if real-comment
		(progn
		  (and (> (point) bol) (setq last-cstart (point)))
		  ;; NOTE Emacs 19 has a misfeature whereby calling
		  ;; parse-partial-sexp with COMMENTSTOP set and with
		  ;; an initial list that says point is in a comment
		  ;; will cause an immediate return.  So we must skip
		  ;; over the comment ourselves.
		  (beginning-of-line 2)))
	    ;; Frob the state to make it look like we aren't in a
	    ;; comment.
	    (setcar (nthcdr 4 state) nil))))
    (and last-cstart
	 (goto-char last-cstart))
    (cons real-comment state)))

(defun cstol-in-comment ()
  "Return t if point is in a comment, and leave point at beginning of comment."
  (let ((save (point)))
    (beginning-of-defun)
    (car (cstol-hairy-scan-for-comment nil save nil))))



;;
;; Help-related code.
;;

(defvar cstol-help-saved-dirs nil
  "Saved help directories.
If `cstol-help-directory-list' changes, this allows `cstol-help-on-word'
to update the alist.")

(defvar cstol-help-alist nil
  "Alist with command names as keys and filenames as values.")

(defun cstol-files-alist (dir &optional alist)
  "Recursively add all pairs (FILE . PATH) under DIR to ALIST."
  (dolist (file (directory-files dir t) alist)
    (cond
     ((not (file-directory-p file))
      (push (cons (file-name-nondirectory file) file) alist))
     ((member (file-name-nondirectory file) '("." "..")))
     (t (setq alist (cstol-files-alist file alist))))))

(defun cstol-help-snarf-commands (dirlist)
  "Return alist of commands and filenames."
  (let ((alist nil))
    (dolist (dir dirlist alist)
      (when (file-directory-p dir)
	(setq alist (cstol-files-alist dir alist))))))

(defun cstol-reread-help-files ()
  "Set up to re-read files, and then do it."
  (interactive)
  (message "Building Cstol help file index...")
  (setq cstol-help-saved-dirs cstol-help-directory-list)
  (setq cstol-help-alist (cstol-help-snarf-commands cstol-help-directory-list))
  (message "Building Cstol help file index...done"))

(defun cstol-word-no-props ()
  "Like `current-word', but strips properties."
  (let ((word (current-word)))
    (set-text-properties 0 (length word) nil word)
    word))

(defun cstol-current-word (flag)
  "Return current command word, or nil.
If FLAG is nil, just uses `current-word'.
Otherwise scans backward for most likely Cstol command word."
  (if (and flag
	   (memq major-mode '(cstol-mode inferior-cstol-mode)))
      (condition-case nil
	  (save-excursion
	    ;; Look backward for first word actually in alist.
	    (if (bobp)
		()
	      (while (and (not (bobp))
			  (not (cstol-real-command-p)))
		(backward-sexp)))
	    (if (assoc (cstol-word-no-props) cstol-help-alist)
		(cstol-word-no-props)))
	(error nil))
    (cstol-word-no-props)))

;;;###autoload
(defun cstol-help-on-word (command &optional arg)
  "Get help on Cstol command.  Default is word at point.
Prefix argument means invert sense of `cstol-use-smart-word-finder'."
  (interactive
   (list
    (progn
      (if (not (equal cstol-help-directory-list cstol-help-saved-dirs))
	  (cstol-reread-help-files))
      (let ((word (cstol-current-word
		   (if current-prefix-arg
		       (not cstol-use-smart-word-finder)
		     cstol-use-smart-word-finder))))
	(completing-read
	 (if (or (null word) (string= word ""))
	     "Help on Cstol command: "
	   (format "Help on Cstol command (default %s): " word))
	 cstol-help-alist nil t nil nil word)))
    current-prefix-arg))
  (if (not (equal cstol-help-directory-list cstol-help-saved-dirs))
      (cstol-reread-help-files))
  (if (string= command "")
      (setq command (cstol-current-word
		     (if arg
			 (not cstol-use-smart-word-finder)
		       cstol-use-smart-word-finder))))
  (let* ((help (get-buffer-create "*Cstol help*"))
	 (cell (assoc command cstol-help-alist))
	 (file (and cell (cdr cell))))
    (set-buffer help)
    (delete-region (point-min) (point-max))
    (if file
	(progn
	  (insert "*** " command "\n\n")
	  (insert-file-contents file))
      (if (string= command "")
	  (insert "Magical Pig!")
	(insert "Cstol command " command " not in help\n")))
    (set-buffer-modified-p nil)
    (goto-char (point-min))
    (display-buffer help)))



;;
;; Other interactive stuff.
;;

(defvar cstol-previous-dir/file nil
  "Record last directory and file used in loading.
This holds a cons cell of the form `(DIRECTORY . FILE)'
describing the last `cstol-load-file' command.")

(defun cstol-load-file (file &optional and-go)
  "Load a Cstol file into the inferior Cstol process.
Prefix argument means switch to the Cstol buffer afterwards."
  (interactive
   (list
    ;; car because comint-get-source returns a list holding the
    ;; filename.
    (car (comint-get-source "Load Cstol file: "
			    (or (and
				 (eq major-mode 'cstol-mode)
				 (buffer-file-name))
				cstol-previous-dir/file)
			    '(cstol-mode) t))
    current-prefix-arg))
  (comint-check-source file)
  (setq cstol-previous-dir/file (cons (file-name-directory file)
				    (file-name-nondirectory file)))
  (cstol-send-string (inferior-cstol-proc)
		   (format inferior-cstol-source-command (cstol-quote file)))
  (if and-go (switch-to-cstol t)))

(defun cstol-restart-with-file (file &optional and-go)
  "Restart inferior Cstol with file.
If an inferior Cstol process exists, it is killed first.
Prefix argument means switch to the Cstol buffer afterwards."
  (interactive
   (list
    (car (comint-get-source "Restart with Cstol file: "
			    (or (and
				 (eq major-mode 'cstol-mode)
				 (buffer-file-name))
				cstol-previous-dir/file)
			    '(cstol-mode) t))
    current-prefix-arg))
  (let* ((buf (if (eq major-mode 'inferior-cstol-mode)
		  (current-buffer)
		inferior-cstol-buffer))
	 (proc (and buf (get-process buf))))
    (cond
     ((not (and buf (get-buffer buf)))
      ;; I think this will be ok.
      (inferior-cstol cstol-application)
      (cstol-load-file file and-go))
     ((or
       (not (comint-check-proc buf))
       (yes-or-no-p
	"A Cstol process is running, are you sure you want to reset it? "))
      (save-excursion
	(comint-check-source file)
	(setq cstol-previous-dir/file (cons (file-name-directory file)
					  (file-name-nondirectory file)))
	(comint-exec (get-buffer-create buf)
		     (if proc
			 (process-name proc)
		       "inferior-cstol")
		     cstol-application file cstol-command-switches)
	(if and-go (switch-to-cstol t)))))))

(defun cstol-auto-fill-mode (&optional arg)
  "Like `auto-fill-mode', but sets `comment-auto-fill-only-comments'."
  (interactive "P")
  (auto-fill-mode arg)
  (if auto-fill-function
      (set (make-local-variable 'comment-auto-fill-only-comments) t)
    (kill-local-variable 'comment-auto-fill-only-comments)))

(defun cstol-electric-hash (&optional count)
  "Insert a `#' and quote if it does not start a real comment.
Prefix arg is number of `#'s to insert.
See variable `cstol-electric-hash-style' for description of quoting
styles."
  (interactive "p")
  (or count (setq count 1))
  (if (> count 0)
      (let ((type
	     (if (eq cstol-electric-hash-style 'smart)
		 (if (> count 3)	; FIXME what is "smart"?
		     'quote
		   'backslash)
	       cstol-electric-hash-style))
	    comment)
	(if type
	    (progn
	      (save-excursion
		(insert ";")
		(setq comment (cstol-in-comment)))
	      (delete-char 1)
	      (and cstol-explain-indentation (message "comment: %s" comment))
	      (cond
	       ((eq type 'quote)
		(if (not comment)
		    (insert "\"")))
	       ((eq type 'backslash)
		;; The following will set count to 0, so the
		;; insert-char can still be run.
		(if (not comment)
		    (while (> count 0)
		      (insert "\\#")
		      (setq count (1- count)))))
	       (t nil))))
	(insert-char ?# count))))

(defun cstol-hashify-buffer ()
  "Quote all `#'s in current buffer that aren't Cstol comments."
  (interactive)
  (save-excursion
    (goto-char (point-min))
    (let (state
	  result)
      (while (< (point) (point-max))
	(setq result (cstol-hairy-scan-for-comment state (point-max) t))
	(if (car result)
	    (beginning-of-line 2)
	  (backward-char)
	  (if (eq ?# (following-char))
	      (insert "\\"))
	  (forward-char))
	(setq state (cdr result))))))

(defun cstol-comment-indent ()
  "Return the desired indentation, but be careful to add a `;' if needed."
  (save-excursion
    ;; If line is not blank, make sure we insert a ";" first.
    (skip-chars-backward " \t")
    (unless (or (bolp) (cstol-real-command-p))
      (insert ";")
      ;; Try and erase a non-significant char to keep charpos identical.
      (if (memq (char-after) '(?\t ?\s)) (delete-char 1))))
  (funcall (default-value 'comment-indent-function)))

;; The following was inspired by the Cstol editing mode written by
;; Gregor Schmid <schmid@fb3-s7.math.TU-Berlin.DE>.  His version also
;; attempts to snarf the command line options from the command line,
;; but I didn't think that would really be that helpful (doesn't seem
;; like it would be right enough.  His version also looks for the
;; "#!/bin/csh ... exec" hack, but that seemed even less useful.
;; FIXME should make sure that the application mentioned actually
;; exists.
(defun cstol-guess-application ()
  "Attempt to guess Cstol application by looking at first line.
The first line is assumed to look like \"#!.../program ...\"."
  (save-excursion
    (goto-char (point-min))
    (if (looking-at "#![^ \t]*/\\([^ \t\n/]+\\)\\([ \t]\\|$\\)")
	(set (make-local-variable 'cstol-application) (match-string 1)))))



;;
;; XEmacs menu support.
;; Taken from schmid@fb3-s7.math.TU-Berlin.DE (Gregor Schmid),
;; who wrote a different Cstol mode.
;; We also have support for menus in Emacs.  We do this by
;; loading the XEmacs menu emulation code.
;;

(defun cstol-popup-menu (e)
  (interactive "@e")
  (popup-menu cstol-mode-menu))



;;
;; Quoting and unquoting functions.
;;

;; This quoting is sufficient to protect eg a filename from any sort
;; of expansion or splitting.  Cstol quoting sure sucks.
(defun cstol-quote (string)
  "Quote STRING according to Cstol rules."
  (mapconcat (lambda (char)
	       (if (memq char '(?[ ?] ?{ ?} ?\\ ?\" ?$ ?\s ?\;))
		   (concat "\\" (char-to-string char))
		 (char-to-string char)))
	     string ""))

;;
;; Bug reporting.
;;


;; These are relics kept "just in case".
(defalias 'cstol-uncomment-region 'uncomment-region)
(defalias 'cstol-indent-for-comment 'comment-indent)
(defalias 'add-log-cstol-defun 'cstol-add-log-defun)
(defalias 'indent-cstol-exp 'cstol-indent-exp)
(defalias 'calculate-cstol-indent 'cstol-calculate-indent)
(defalias 'cstol-beginning-of-defun 'beginning-of-defun)
(defalias 'cstol-end-of-defun 'end-of-defun)
(defalias 'cstol-mark-defun 'mark-defun)
(defun cstol-mark () (mark t))

(provide 'cstol-mode)

(add-to-list 'auto-mode-alist '("\\.prc\\'" . cstol-mode))


;;; cstol.el ends here
